// 使用D8内置的readbuffer函数读取Wasm文件
const buffer = readbuffer("/home/sjk/桌面/asc_test/build/sin_sum2.wasm");

// 定义一个函数来初始化和实例化WebAssembly模块
async function instantiateWasm(buffer) {
    const importObject = {
        env: {
            abort: function (message, fileName, lineNumber, columnNumber) {
                message = __liftString(message >>> 0);
                fileName = __liftString(fileName >>> 0);
                lineNumber = lineNumber >>> 0;
                columnNumber = columnNumber >>> 0;
                throw new Error(`${message} in ${fileName}:${lineNumber}:${columnNumber}`);
            }
        }
    };

    const module = await WebAssembly.compile(buffer);
    const instance = await WebAssembly.instantiate(module, importObject);

    // 初始化内存视图和其他必要的函数
    const memory = instance.exports.memory;
    const dataview = new DataView(memory.buffer);

    // 定义检查ArrayBuffer是否分离的函数
    function isArrayBufferDetached(arrayBuffer) {
        try {
            new DataView(arrayBuffer);
            return false;
        } catch (e) {
            if (e.message.includes('detached')) {
                return true;
            }
            throw e;
        }
    }

    // 函数用于将JavaScript数组转换为WebAssembly线性内存中的格式
    function lowerArray(values, align, elementSize) {
        const length = values.length;
        const bufferSize = length * elementSize;
        const buffer = instance.exports.__pin(instance.exports.__new(bufferSize, 1)) >>> 0;
        const header = instance.exports.__pin(instance.exports.__new(16, 2)) >>> 0;

        // 验证内存状态
        if (isArrayBufferDetached(memory.buffer)) {
            console.error('ArrayBuffer is detached prematurely in lowerArray!');
            throw new Error('Memory buffer detached unexpectedly in lowerArray');
        }

        dataview.setUint32(header + 0, buffer, true);
        dataview.setUint32(header + 4, buffer, true);
        dataview.setUint32(header + 8, bufferSize, true);
        dataview.setUint32(header + 12, length, true);

        for (let i = 0; i < length; i++) {
            // 每次操作前再次验证内存状态
            if (isArrayBufferDetached(memory.buffer)) {
                console.error('ArrayBuffer is detached prematurely in lowerArray loop!');
                throw new Error('Memory buffer detached unexpectedly in lowerArray loop');
            }
            dataview.setUint32(buffer + (i * elementSize), values[i], true);
        }

        return {
            buffer,
            header
        };
    }

    // 函数用于从WebAssembly线性内存中提取字符串
    function liftString(pointer) {
        if (!pointer) return null;
        const end = pointer + new Uint32Array(memory.buffer)[pointer - 4 >>> 2] >>> 1;
        const memoryU16 = new Uint16Array(memory.buffer);
        let string = '';
        for (let i = pointer >>> 1; i < end; i++) {
            string += String.fromCharCode(memoryU16[i]);
        }
        return string;
    }

    // 返回适配后的导出对象
    return {
        memory,
        dataview,
        lowerArray,
        calculateSinSumWithArray: (numbers) => {
            const { buffer: arrayBuffer, header: arrayHeader } = lowerArray(numbers, 4, 4); // 假设是32位整数数组
            // 验证内存状态
            if (isArrayBufferDetached(memory.buffer)) {
                console.error('ArrayBuffer is detached prematurely in calculateSinSumWithArray!');
                throw new Error('Memory buffer detached unexpectedly in calculateSinSumWithArray');
            }
            const result = instance.exports.calculateSinSumWithArray(arrayHeader);
            instance.exports.__unpin(arrayBuffer);
            instance.exports.__unpin(arrayHeader);
            return result;
        }
    };
}

// 测试函数
async function test() {
    const wasmFunctions = await instantiateWasm(buffer);
    const numbers = new Array(1000).fill(0).map((_, index) => index + 1);

    // 测量时间
    const iterations = 100;
    const startTime = Date.now();
    let totalResult = 0;

    for (let i = 0; i < iterations; i++) {
        const result = wasmFunctions.calculateSinSumWithArray(numbers);
        totalResult += result;
    }

    const endTime = Date.now();

    // 输出结果和耗时
    console.log(`Total Result: ${totalResult}, Total Time: ${endTime - startTime}ms, Average Time: ${(endTime - startTime) / iterations}ms`);
}

// 运行测试
test().catch(err => console.log(`Error: ${err}`));